<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <strong style="font-size: 20px;">
          新增工资发放
        </strong>
      </el-col>
      <el-col :span="8" align="middle">
        <strong style="font-size: 16px;">
          账户余额:{{ balance }}
        </strong>
      </el-col>
      <el-col :span="12" align="right">
        <span style="margin-right: .5em">
          <el-switch
            v-model="isAll"
            inactive-text="显示所有成员"
            size="medium"
            @change=" showStaffs()"
          />
        </span>
        <span style="margin-right: .5em">
          <el-select v-model="squad" style="width: 150px;" clearable placeholder="小队" @change="showStaffs()">
            <el-option v-for="item in squads" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </span>
        <el-button @click="rateDialog.visible = true">设置费率</el-button>
      </el-col>
    </el-row>
    <div v-if="store" style="width: 100%;">
      <el-table
        :key="refreshStaff"
        v-loading="loadingStaff"
        :data="salaryData"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        show-summary
        :summary-method="getSummaries"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column fixed prop="name" label="员工" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.isTransfer" style="color:red">{{ scope.row.name }}({{ scope.row.id }})</span>
            <span v-else>{{ scope.row.name }}({{ scope.row.id }})</span>
          </template>
        </el-table-column>
        <el-table-column fixed prop="squadName" label="小队" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.isTransfer" style="color:red">{{ scope.row.squadName }}</span>
            <span v-else>{{ scope.row.squadName }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed prop="phone" label="电话" width="110">
          <template slot-scope="scope">
            <span v-if="scope.row.isTransfer" style="color:red">{{ scope.row.phone }}</span>
            <span v-else>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed prop="dailyWage" label="日薪" width="100" />
        <el-table-column prop="onDate" label="上班打卡时间" width="170" />
        <el-table-column prop="offDate" label="落班打卡时间" width="170" />
        <el-table-column label="费率" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.platformFeeRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="penalty" label="奖罚金额">
          <template slot-scope="scope">
            <el-input v-model="scope.row.penalty" type="number" @blur="sumList()" />
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额(为0不下发)" />
        <el-table-column label="备注">
          <template slot-scope="scope">
            <el-input v-model="scope.row.comment" />
          </template>
        </el-table-column>
      </el-table>
      <div style="padding-top:10px">
        <el-button type="primary" @click="uploadReady()">确 定 发 放</el-button>
      </div>
    </div>

    <el-dialog
      title="支付设置"
      :visible.sync="dialog.visible"
      width="40%"
    >
      <div style="padding: 10px;">
        <el-row type="flex" align="middle" style="padding-bottom:10px">
          <el-col :span="4"><strong>支付密码</strong></el-col>
          <el-col :span="20">
            <el-input v-model="dialog.password" type="password" show-password />
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 10px;" @click="dialog.visible = false">取消</el-button>
        <el-button slot="reference" type="primary" :loading="dialog.loading" @click="submit()">
          {{ dialog.loading ? '提交中 ...' : '确认' }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="费率设置"
      :visible.sync="rateDialog.visible"
      width="40%"
    >
      <div style="padding: 10px;">
        <el-row type="flex" align="middle" style="padding-bottom:10px">
          <el-col :span="4"><strong>抽取费率(%)</strong></el-col>
          <el-col :span="12">
            <el-input v-model="rateDialog.platformFeeRate" type="number" />
          </el-col>
          <el-col :span="8">
            <span style="padding: 10px 10px">
              <el-button type="success" size="small" plain @click="defalultRate">默认费率</el-button>
            </span>
          </el-col>
        </el-row>
        <el-row type="flex" align="middle">
          <el-col :span="4"><strong>示例</strong></el-col>
          <el-col :span="20">
            <div>实际金额的扣减,如发放100的时候</div>
            <div>实际发放为(1-{{ rateDialog.platformFeeRate }}%)*100</div>
            <div>实际金额{{ ((1-(parseFloat(rateDialog.platformFeeRate)/100))*100).toFixed(2) }}</div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="margin-right: 10px;" @click="rateDialog.visible = false">取消</el-button>
        <el-button slot="reference" type="primary" @click="submitRate()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loadingStaff: false,
      refreshStaff: 0,
      staffs: [],
      salaryData: [],
      store: null,

      balance: 0,
      dialog: {
        visible: false,
        password: null,
        loading: false
      },
      rateDialog: {
        platformFeeRate: 0,
        visible: false
      },
      send: [],
      yesterday: null,
      today: null,
      tomorrow: null,
      squad: null,
      squads: [],
      isAll: false
    }
  },
  async created() {
    const user = await this.axios.get(`/api/user`, { params: {
      '@expands': `['entity.officer.store']`
    }})
    if (!user.data.paymentPassword) {
      this.$message.warning('账号未设置支付密码,请在右上角选择重置支付密码！')
    }
    this.store = user.data.officer?.__metadata.store?.__metadata
    if (!this.store.user) {
      this.$message.error('获取主账号信息失败！')
      return
    }
    const yesterday = new Date(Date.now() - 86400000)
    const today = new Date()
    const tomorrow = new Date(Date.now() + 86400000)
    this.yesterday = `${yesterday.getFullYear()}/${yesterday.getMonth() + 1}/${yesterday.getDate()}`
    this.today = `${today.getFullYear()}/${today.getMonth() + 1}/${today.getDate()}`
    this.tomorrow = `${tomorrow.getFullYear()}/${tomorrow.getMonth() + 1}/${tomorrow.getDate()}`
    console.log('3 day', this.yesterday, this.today, this.tomorrow)

    this.defalultRate()
    this.getSquads()
    this.getBalance()
    this.getStaffs()
  },
  methods: {
    getBalance() {
      if (this.store.user) {
        this.axios.get(`/officer/balances`, { params: {
          '@filter': `entity.getUser().getId() == ${this.store.user.id}`
        }}).then(res => {
          this.balance = res.data[0].amount
        })
      }
    },
    getSquads() {
      this.axios.get(`/officer/squads`, {
        params: {
          limit: 10000000
        }
      }).then(res => {
        this.squads = res.data
      })
    },
    getStaffs() {
      this.loadingStaff = true
      this.axios.get(`/officer/staffs`, { params: {
        '@display': `{
              'id': 'entity.getId()',
              'name': 'entity.getName()',
              'phone': 'entity.getPhone()',
              'user': 'entity.getUser().getId()',
              'squadId': 'entity.getSquad().getId()',
              'squadName': 'entity.getSquad().getName()',
              'dailyWage': 'entity.getDailyWage()'
          }`,
        '@filter': 'entity.getEnabled() == true',
        'limit': 100000000
      }})
        .then((res) => {
          const staffs = res.data
          staffs.map(s => {
            s.penalty = null
            s.platformFeeRate = this.rateDialog.platformFeeRate
            s.amount = Number(s.dailyWage)
            s.comment = null
          })
          this.axios.get(`/officer/attendance-records`, { params: {
            '@display': `{
              'id': 'entity.getId()',
              'staffId': 'entity.getStaff().getId()',
              'staffName': 'entity.getStaff().getName()',
              'date': 'entity.getDate().format("Y-m-d")',
              'storeId': 'entity.getStore().getId()',
              'storeName': 'entity.getStore().getName()',
              'typeId': 'entity.getType().getId()',
              'typeName': 'entity.getType().getName()',
              'startTime' : 'entity.getStartTime().format("Y-m-d H:i:s")',
              'endTime' : 'entity.getEndTime().format("Y-m-d H:i:s")'
          }`,
            '@filter': `entity.getDate() >= datetime.get('${this.yesterday} 00:00:00')
                 && entity.getDate() <= datetime.get('${this.yesterday} 23:59:59')`,
            'limit': 100000000
          }})
            .then((log) => {
              this.axios.get(`/officer/transactions`, { params: {
                '@display': `{
                      'id': 'entity.getId()',
                      'fromId': 'entity.getFrom().getId()',
                      'toId': 'entity.getTo().getId()'
                      }`,
                '@filter': `entity.getType() matches "salary" && entity.getFrom().getId() == ${this.store.user.id}
                            && entity.getCreatedTime() >= datetime.get('${this.today} 00:00:00')
                            && entity.getCreatedTime() <= datetime.get('${this.today} 23:59:59')`,
                'limit': 100000000
              }})
                .then((transaction) => {
                  const logs = log.data
                  const transactions = transaction.data
                  const array = []
                  for (var datum of staffs) {
                    // find 打卡记录筛选staff
                    const log = logs.find(v => v.staffId === datum.id)
                    const item = datum
                    if (!log) {
                      item.onDate = ''
                      item.offDate = ''
                      item.typeId = 0
                      item.typeName = ''
                    } else {
                      item.onDate = log.startTime ? log.startTime : ''
                      item.offDate = log.endTime ? log.endTime : ''
                      item.typeId = log.typeId
                      item.typeName = log.typeName
                    }
                    // find transaction筛选staff
                    const trs = transactions.find(v => v.toId === datum.user)
                    if (!trs) {
                      item.isTransfer = false
                    } else {
                      item.isTransfer = true
                    }
                    array[datum['id']] = item
                  }
                  const data = []
                  for (var i of Object.keys(array)) {
                    data.push(array[i])
                  }
                  this.staffs = data
                  this.sumList()
                  this.showStaffs()
                })
                .finally(() => { this.loadingStaff = false })
            })
            .catch(() => { this.loadingStaff = false })
        })
        .catch(() => { this.loadingStaff = false })
    },
    showStaffs() {
      const data = this.staffs
      let isAllData = []
      let squadData = []
      if (!this.isAll) {
        // staffs typeId判断是否打卡
        isAllData = data.filter(v => v.typeId > 0)
      } else {
        isAllData = data
      }
      if (this.squad) {
        squadData = isAllData.filter(v => v.squadId === this.squad)
      } else {
        squadData = isAllData
      }
      this.salaryData = squadData
      console.log(this.salaryData.length)
    },
    defalultRate() {
      const platformFeeRate = this.store.config && this.store.config.transactionFeeRate ? this.store.config.transactionFeeRate : 0
      this.rateDialog.platformFeeRate = (platformFeeRate * 100).toFixed(2)
    },
    submitRate() {
      if (this.rateDialog.platformFeeRate > 100 || this.rateDialog.platformFeeRate < 0) {
        this.$message.error('抽取费率应在0-100之间')
        return
      }
      this.staffs.map(v => { v.platformFeeRate = this.rateDialog.platformFeeRate })
      this.sumList()
      this.rateDialog.visible = false
    },
    sumList() {
      this.staffs.map(v => {
        const customFeeRate = Number(v.platformFeeRate) / 100
        const penalty = Number(v.penalty)
        if (penalty) {
          v.amount = ((Number(v.dailyWage) + penalty) * (1 - customFeeRate)).toFixed(2)
        } else {
          v.amount = (Number(v.dailyWage) * (1 - customFeeRate)).toFixed(2)
        }
      })
    },
    uploadReady() {
      const data = []
      for (var i of this.salaryData) {
        if (i.amount) {
          if (i.amount < 0) {
            this.$message.error('禁止填负数')
            return
          }
          if (i.amount > 0) {
            data.push({
              to: i.user,
              amount: i.amount,
              type: 'salary',
              comment: i.comment
            })
          }
        }
      }
      if (data.length === 0) {
        this.$message.error('请为发放员工填写金额')
        return
      }
      this.send = data
      this.dialog.visible = true
    },
    submit() {
      if (!this.dialog.password) {
        this.$message.error('请输入验证密码')
        return
      }
      if (this.send.length === 0) {
        this.$message.error('没有可用数据')
        return
      }
      this.dialog.loading = true
      this.axios.post(`/api/user/validate-password`, {
        password: this.dialog.password,
        payment: 1 })
        .then(res => {
          this.dialog.password = null
          this.dialog.visible = false

          const loading = this.$loading({
            lock: true,
            text: '数据交互中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.axios.post(`/officer/transactions/send`, this.send).then(res => {
            this.$message.success('数据上送成功')
            this.$router.go(-1)
          }).finally(() => {
            loading.close()
          })
        })
        .finally(() => { this.dialog.loading = false })
    },
    getSummaries(param) {
      const { columns, data } = param
      const sums = []

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (index === 3 || index === 7 || index === 8) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0).toFixed(2)
          // sums[index] += ' 元'
        } else {
          sums[index] = ''
        }
      })
      return sums
    }
  }
}
</script>
